﻿using LuckyShell;

var interpreter = new Interpreter();

if (args.Length > 0)
{
    interpreter.Run(File.ReadAllText(args[0]));
    if (interpreter.Error.Count != 0)
    {
        foreach (var item in interpreter.Error) Console.WriteLine(item);
        interpreter.Error.Clear();
    }
    return;
}

while (true)
{
    try
    {
        Console.Write("> ");
        var code = Console.ReadLine();
        if (string.IsNullOrEmpty(code)) continue;
        if (code == "exit") return;
        if (code.StartsWith("test"))
        {
            var testString = code.Split(" ")[^1];
            Test(interpreter, testString == "test" ? "" : testString);
            continue;
        }
        if (code.StartsWith("-f"))
        {
            var file = code.Split(" ")[^1];
            code = File.ReadAllText(file);
            code += $"{Environment.NewLine}pass";
        }

        interpreter.Run(code);
        if (interpreter.Error.Count != 0)
        {
            foreach (var item in interpreter.Error) Console.WriteLine(item);
            interpreter.Error.Clear();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine($"Error: {e.Message}");
    }
}

void Test(Interpreter i, string testString = "")
{
    i.Init(new VariateManager());
    var codeTest = Api.Test(testString);
    codeTest += $"{Environment.NewLine}pass";
    i.RunTest(codeTest);
    foreach (var item in i.Error) Console.WriteLine(item);
    Console.WriteLine(i.Time);
}